import Cocoa
import os.log

class ScreenshotManager {
    private var overlayWindow: NSWindow?
    private var overlayView: ScreenshotOverlayView?
    private var floatingWindows: Set<FloatingWindow> = []
    private let logger = OSLog(subsystem: "com.macscreenshot", category: "ScreenshotManager")
    
    init() {
        os_log("ScreenshotManager initialized", log: logger, type: .info)
        // 监听截图通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleTakeScreenshot),
            name: .takeScreenshot,
            object: nil
        )
    }
    
    deinit {
        os_log("ScreenshotManager being deallocated", log: logger, type: .info)
        NotificationCenter.default.removeObserver(self)
        floatingWindows.forEach { $0.close() }
        floatingWindows.removeAll()
    }
    
    @objc private func handleTakeScreenshot() {
        os_log("Screenshot triggered via notification", log: logger, type: .info)
        takeScreenshot()
    }
    
    func takeScreenshot() {
        os_log("Starting screenshot process", log: logger, type: .info)
        
        // 获取主屏幕
        guard let screen = NSScreen.main else {
            os_log("Failed to get main screen", log: logger, type: .error)
            return
        }
        
        // 创建一个覆盖整个屏幕的窗口
        overlayWindow = NSWindow(
            contentRect: screen.frame,
            styleMask: [.borderless],
            backing: .buffered,
            defer: false
        )
        
        guard let window = overlayWindow else {
            os_log("Failed to create overlay window", log: logger, type: .error)
            return
        }
        
        os_log("Created overlay window with frame: %{public}@", log: logger, type: .info, String(describing: window.frame))
        
        // 设置窗口属性
        window.level = .floating
        window.backgroundColor = .clear
        window.isOpaque = false
        window.hasShadow = false
        window.ignoresMouseEvents = false
        
        // 创建覆盖层视图
        overlayView = ScreenshotOverlayView(frame: window.contentView?.bounds ?? .zero)
        
        // 设置截图完成的回调
        overlayView?.onScreenshotComplete = { [weak self] image in
            guard let self = self else { return }
            
            // 关闭遮罩窗口
            self.overlayWindow?.close()
            self.overlayWindow = nil
            self.overlayView = nil
            
            if let screenshot = image {
                // 创建浮动窗口
                let floatingWindow = FloatingWindow(image: screenshot, origin: NSPoint(x: 100, y: 100))
                self.floatingWindows.insert(floatingWindow)
                floatingWindow.makeKeyAndOrderFront(nil)
                os_log("Created floating window for screenshot", log: self.logger, type: .info)
            } else {
                os_log("Screenshot cancelled or failed", log: self.logger, type: .info)
            }
        }
        
        if let overlayView = overlayView {
            window.contentView?.addSubview(overlayView)
        }
        
        window.makeKeyAndOrderFront(nil)
    }
}
